#-*- coding: UTF-8 -*-

# For regular expressions
import re
# Random string
import random

# Placement of commands
commandFiles = ['commands.txt']

# Class for messages
class Messages:
    cmds_general = {}
    cmds_users = {}

    def parseFile(self, file):
        """Load content of file"""
        d = open(file, "r")
        empty = re.compile("#|^[ ]*$")
        string_double_quotes = re.compile('^[ ]*"(.*)"[ ]*(\[.*\]|)[ ]*(PM|)[ ]*=[ ]*"(.*)"[ ]*$')

        for line in d.read().splitlines():
            if not empty.match(line):
                double_quotes = string_double_quotes.match(line)
                if double_quotes:
                    name = double_quotes.group(1).lower()
                    user = double_quotes.group(2).strip('[ ]')
                    pm = double_quotes.group(3)=="PM"
                    value = double_quotes.group(4).split('", "')
                else:
                    print line
                    raise ValueError, "Bad format of file {0}".format(file)

                if user:
                    if not self.cmds_users.has_key(name):
                        self.cmds_users[name] = {}

                    self.cmds_users[name][user] = (value, pm)
                else:
                    self.cmds_general[name] = (value, pm)

        d.close()

    def __init__(self, cmdFiles):
        """Load files into memory"""
        self.cmdFiles = cmdFiles
        for file in self.cmdFiles:
            self.parseFile(file)
    
    def decode(self, text, user):
            response = random.choice(text).decode('utf-8')
            return response.replace("%USER", user)

    def check(self, name, user):
        """Check if cmd is avaible"""

        key = name.lower().strip()

        if self.cmds_users.has_key(key) and self.cmds_users[key].has_key(user):
            # User specified message
            response, pm = self.cmds_users[key][user]
            response = self.decode(response, user)

            return (response, pm)

        elif self.cmds_general.has_key(key):
            # General user message
            response, pm = self.cmds_general[key]
            response = self.decode(response, user)

            return (response, pm)
        else:
            return (None, False)

if __name__ == "__main__":
    m = Messages(commandFiles)

    queue = ["    iyo     ", "iYo", "iyO", "nič", "olinka", "user", ":'(", "mas me rada?"]
    users = ["iyo", "polo", "Olinka"]

    for msg in queue:
        print "%s => '%s'"%(msg, m.check(msg, random.choice(users)))
